﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using SlamCms.Data.Repositories;
using SlamCms.Web.HttpHandlers;
using SlamCms.Web.Mvc;

namespace SlamCms.Web
{
	public class UrlHandlerRouterRegistrar
	{
		private readonly Lazy<IUrlHandlerRepository> _urlHandlerRepository;

		public UrlHandlerRouterRegistrar(Lazy<IUrlHandlerRepository> urlHandlerRepository)
		{
			_urlHandlerRepository = urlHandlerRepository;
		}

		public void RegisterRoutes(RouteCollection routes)
		{
			var urlHandlers = _urlHandlerRepository.Value.GetAll().Where(x => x.StatusCode != 404);

			using (routes.GetWriteLock())
			{
				// remove the old routes
				var routesToRemove = routes.Where(x => x is Route && ((Route)x).DataTokens != null && ((Route)x).DataTokens.ContainsKey("urlhandler")).ToList();
				foreach (var route in routesToRemove)
					routes.Remove(route);

				// add the new ones
				var position = 0;
				foreach (var urlHandler in urlHandlers)
				{
					var url = urlHandler.Url.TrimStart('/');
					var to = urlHandler.RedirectUrl;
					var permanent = urlHandler.StatusCode == 301;
					var redirectRoute = new Route(url, new RedirectHttpHandler(to, permanent, isReusable: false))
													.AddDataToken("urlhandler", urlHandler.UrlHandlerId)
													.AddConstraints(new IncomingOnlyRouteConstraint());
					routes.Insert(position, new NormalizeRoute(redirectRoute));
					position++;	  
				}
			}
		}
	}
}
